<?php
namespace Com\Pay;

//通联微信公众号支付

class XGzhPay{

    private $config = array();

    public function __construct($mchConfig){
        $this->config = $mchConfig;
    }

    /*生成支付连接*/
    public function getUrl($order_info,$other = array()){
        $price = $order_info['paymoney'];
//        $returnUrl = $order_info['return_url'];
        $notifyUrl = S_URL . '/Api/NotifyCallback/XGzhNotifyGzh';
        $order_sn = $order_info['ordernumber'];
        $post_data = array(
            "merNo" => $this->config['mch_id'],
            "orderNo" => $order_sn,
            "amount" => $price * 100,
            "reqId" => $order_sn,
            "reqTime" => date('YmdHis'),
            "subAppId" => $this->config['appid'],
            "subOpenId" => $order_info['openid'],
            "notifyUrl" => $notifyUrl,
            "goodsName" => "Changbao",
        );

        $post_data['signIn'] = $this->setSign($post_data,$this->config['mch_key'],false);
        $tar_url = 'http://scp.yufu99.com/scanpay-api/api/wxGZHUnifiedOrder20';
        $res = json_decode($this->https_request($tar_url,$post_data),true);
        dump($res);die;
        if($res['result'] == '0000'){
           return $res;
        }
        return false;
    }


    // 生成签名方法
    private function setSign($param,$key,$IS_Notify){
        $str = "";
        ksort($param);
        foreach($param as $key1=>$val)  {
            if($IS_Notify && $key1 == 'signIn') continue;
            $str.=$key1."=".$val."&";
        }
        $str = rtrim($str,'&');
        $sign = strtoupper(md5($str . $key));
        return $sign;
    }


    //回调方法，把返回数据处理成统一规定返回
    public function response($data){
        $Mysign = $this->setSign($data,$this->config['mch_key'],true);
        if($Mysign === $data['signIn']){
            return true;
        }else{
            // 失败
            return false;
        }
    }

    function https_request($url, $data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

        //参数不为空则为post请求

        if (!empty($data)){

            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

}
